package org.example.node;

/**
 * @author liyishan
 * @date 2024/10/14 10:16
 * @apiNote
 */

public class BMReverseBetween {
    public static void main(String[] args) {
        ListNode head = new ListNode(9);
        head.next = new ListNode(7);
        head.next.next = new ListNode(2);
        head.next.next.next = new ListNode(5);
        head.next.next.next.next = new ListNode(4);
        head.next.next.next.next.next = new ListNode(3);
        head.next.next.next.next.next.next = new ListNode(6);
        BMReverseBetween reverseBetween = new BMReverseBetween();
        ListNode result = reverseBetween.reverseBetween(head, 3, 6);

        while (result != null) {
            System.out.print(result.val + " -> ");
            result = result.next;
        }
    }

    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummpy = new ListNode(-1,head);
        ListNode pre = dummpy;
        for(int i =0;i<m-1;i++){
            pre = pre.next;
        }
        ListNode cur = pre.next;
        for(int i = 0;i<n-m;i++){
            ListNode next = cur.next;
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
        }
        return dummpy.next;
    }
}
